package com.jxl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jxl.constant.MessageConstant;
import com.jxl.constant.PasswordConstant;
import com.jxl.constant.StatusConstant;
import com.jxl.entity.context.UserHolder;
import com.jxl.entity.dto.UpdatePasswordDTO;
import com.jxl.entity.dto.UserLoginDTO;
import com.jxl.entity.po.Schedule;
import com.jxl.entity.po.User;
import com.jxl.entity.query.UserPageQuery;
import com.jxl.entity.vo.PageResponse;
import com.jxl.entity.vo.UserVO;
import com.jxl.exception.BaseException;
import com.jxl.mapper.UserMapper;
import com.jxl.service.IScheduleService;
import com.jxl.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 金小梁
 * @since 2025-06-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IScheduleService scheduleService;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = query().eq("username", username).one();

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对进行md5加密，然后再进行比对
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new BaseException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new BaseException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 分页查询
     *
     * @param userPageQuery
     * @return
     */
    @Override
    public PageResponse<UserVO> queryUsers(UserPageQuery userPageQuery) {
        PageHelper.startPage(userPageQuery.getPageNum(),  userPageQuery.getPageSize());
        Page<UserVO> userVOPage = userMapper.selectByPageQuery(userPageQuery);
        PageResponse<UserVO> pageResponse = PageResponse.of(userVOPage,  UserVO.class);
        return pageResponse;
    }

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    public void saveUser(User user) {
        //判断用户名是否已经存在
        List<User> list = query().eq("username", user.getUsername()).list();
        if (list.size() > 0) {
            throw new BaseException("用户名已存在,请重新填写");
        }
        //员工编号也要进行判断
        List<User> list1 = query().eq("emp_no", user.getEmpNo()).list();
        if (list1.size() > 0) {
            throw new BaseException("员工编号已存在,请重新填写");
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //将密码进行加密，默认为123456
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        user.setPassword(password);
        save(user);
    }

    /**
     * 删除用户
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        //查询该用户是否在排班表中被安排
        ids.forEach(id -> {
            List<Schedule> list = scheduleService.query().eq("user_id", id).list();
            if (list.size()>0) {
                throw new BaseException("该用户正在被排班，请先取消排班");
            }
        });
        removeByIds(ids);
    }


    /**
     * 修改用户
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {
        //判断用户名是否已经存在，排除当前修改的
        List<User> list = query().eq("username", user.getUsername()).ne("id", user.getId()).list();
        if (list.size() > 0) {
            throw new BaseException("用户名已存在,请重新填写");
        }
        //员工编号也要进行判断，排除当前修改的
        List<User> list1 = query().eq("emp_no", user.getEmpNo()).ne("id", user.getId()).list();
        if (list1.size() > 0) {
            throw new BaseException("员工编号已存在,请重新填写");
        }
        updateById(user);
    }

    /**
     * 修改密码
     *
     * @param
     */
    @Override
    public void updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        Long userId = UserHolder.getUser().getId();
        User user = query().eq("id", userId).one();
        if (user == null) {
            throw new BaseException("用户不存在");
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(updatePasswordDTO.getOldPassword().getBytes()))) {
            throw new BaseException("旧密码错误");
        }
        //将密码进行加密
        String password = DigestUtils.md5DigestAsHex(updatePasswordDTO.getNewPassword().getBytes());
        user.setPassword(password);
        updateById(user);
    }
}
